package com.ucode.springboot.starter.base.utils;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * spring获取bean工具类
 * @author: liliang
 * @date: 2019年12月16日 下午9:00:43
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    public static <T> T getBean(Class<T> cla) {
        return applicationContext.getBean(cla);
    }

    public static <T> T getBean(String name, Class<T> cal) {
        return applicationContext.getBean(name, cal);
    }
    
    public static <T> List<T> getBeansOfType(Class<T> clazz) {
        Map<String, T> map = applicationContext.getBeansOfType(clazz);
        return map == null ? null : new ArrayList<>(map.values());
    }
    
    /**
     * 获取所有被注解的 bean
     */
    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> anno) {
        Map<String, Object> map = applicationContext.getBeansWithAnnotation(anno);
        return map;
    }

    public static String getProperty(String key) {
        return applicationContext.getBean(Environment.class).getProperty(key);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringBeanUtil.applicationContext = applicationContext;
    }
}